package com.yuehuanghun.admin.generator.model.generator;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class TableGeneratorManager implements ApplicationContextAware  {
	private static ApplicationContext applicationContext;
	private static final Map<String, TableGenerator> TABLE_GENERATOR_MAP = new HashMap<>();
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		TableGeneratorManager.applicationContext = applicationContext;
	}

	@Autowired
	private void init(ObjectProvider<List<TableGenerator>> generatorProvider) {
		generatorProvider.ifAvailable(list -> {
			list.forEach(generator -> {
				TABLE_GENERATOR_MAP.put(generator.getDbName(), generator);
			});
		});
	}
	
	public static TableGenerator getTableGenerator(String dbName) {
		TableGenerator tableGenerator = TABLE_GENERATOR_MAP.get(dbName);
		if(tableGenerator == null) {
			return TABLE_GENERATOR_MAP.get(DefaultTableGenerator.DB_NAME);
		}
		return applicationContext.getBean(tableGenerator.getClass());
	}
}
